// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

var eventManager = require("event_manager");
var user = require("user");
var config = require("config")
var handler = require("handler")
var dataManager = require("data_manager")

var getDate = function(sces) {
    var days = Math.floor(sces / 60 / 60 / 24) + "天";
    var hours = Math.floor(sces / 60 / 60) % 24 + "时";
    var min = Math.floor(sces / 60) % 60 + "分";
    var sec = sces % 60 + "秒";
    return hours + min + sec;
}

var leftTimer = function(year,month,day,hour,minute,second){
    var checkTime = function(i) {
        if(i<10){
            i = "0" + i;
        } 
        return i;
    }
    var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //计算剩余的毫秒数 
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); //计算剩余的天数 
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); //计算剩余的小时 
    var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
    var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
    days = checkTime(days); 
    hours = checkTime(hours); 
    minutes = checkTime(minutes); 
    seconds = checkTime(seconds); 
    return days+"天" + hours+"小时" + minutes+"分"+seconds+"秒";
}

var marketItem = function(id, price) {
    this.id = id;
    this.price = price;
}

cc.Class({
    extends: cc.Component,

    properties: {
        nick: cc.Label,
        power: cc.Label,
        wit: cc.Label,
        strength: cc.Label,
        luck: cc.Label,

        birthArea: cc.Label,

        // explore
        exploreBtn: cc.Button,
        exploreLabel: cc.Label,
        time: cc.Label,
        exploreAttrPower: cc.Label,
        exploreAttrWish: cc.Label,
        exploreAttrStrength: cc.Label,
        exploreAttrLuck: cc.Label,

        // jiangchi
        refreshTime: cc.Label,

        // item
        item: cc.Prefab,

        // bag
        bagDataList: cc.ScrollView,
        foodNode: cc.Node,

        // store
        storeDataList: cc.ScrollView,

        // newland
        newLand: cc.Prefab,

        // market
        marketPrefab: cc.Prefab,
        marketDataList: cc.ScrollView,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._time = 0;
        this.exploreLabel.node.active = false;
        this.time.node.active = false;

        eventManager.register(eventManager.PLAYER_CREATED_FAIL, this, this.onCreatPlayerFail);
        handler.getPlayer();

        this._refresh();
        this._refreshJiangChi();
        this._refreshExploreData();
        this._refreshStore();
        this._refreshMarket();

        eventManager.register(eventManager.ITEM_TYPE_CHANGE, this, this.onItemChange);
        eventManager.register(eventManager.EXPLORE_FINISH, this, this.onExploreFinish);
        eventManager.register(eventManager.DATA_CHANGE, this, this.onDataChange);
    },

    onDestroy: function() {
    },

    onCreatPlayerFail: function() {
        this.scheduleOnce(function() {
            handler.getPlayer();
        }, 1);
    },

    _refresh: function() {
        this.nick.string = user.nick;
        this.power.string = "力量：" + user.power;
        this.wit.string = "智力：" + user.wit;
        this.strength.string = "体力：" + user.strength;
        this.luck.string = "幸运：" + user.luck;
    },

    _refreshJiangChi: function() {
        var self = this;
        this.schedule(function() {
            var timeString = leftTimer(2018, 6, 30, 12, 59, 59);
            self.refreshTime.string = timeString + " 后刷新";
        }, 1);
    },

    _refreshExploreData: function() {
        this.exploreAttrPower.string = "力量调整值：" + user.power;
        this.exploreAttrWish.string = "智力调整值：" + user.wit;
        this.exploreAttrStrength.string = "体力调整值：" + user.strength;
        this.exploreAttrLuck.string = "幸运调整值：" + user.luck;

        // 物品增加属性
        var children = this.bagDataList.content.children;
        var addpower = 0;
        var addwit = 0;
        var addstrength = 0;
        var addluck = 0;
        for (var i = 0; i < children.length; ++i) {
            var itemNodeObj = children[i].getComponent("item_node").getItem();
            if (itemNodeObj.valid) {
                addpower = addpower + itemNodeObj.power;
                addwit = addwit + itemNodeObj.wit;
                addstrength = addstrength + itemNodeObj.strength;
                addluck = addluck + itemNodeObj.luck;
            }
        }
        if (addpower > 0) {
            this.exploreAttrPower.string = "力量调整值：" + user.power + "  + " + addpower;
        }
        if (addwit > 0) {
            this.exploreAttrWish.string = "智力调整值：" + user.wit + "  + " + addwit;
        }
        if (addstrength > 0) {
            this.exploreAttrStrength.string = "体力调整值：" + user.strength + "  + " + addstrength;
        }
        if (addluck > 0) {
            this.exploreAttrLuck.string = "幸运调整值：" + user.luck + "  + " + addluck;
        }
    },

    _refreshStore: function() {
        // get table, there is a item
        this.storeDataList.content.removeAllChildren();
        var itemList = dataManager.getItemList();
        for (var i = 0; i < itemList.length; ++i) {
            var itemObj = itemList[i];
            if (itemObj) {
                for (var j = 0; j < itemObj.useCount; ++j) {
                    var itemNode = cc.instantiate(this.item);
                    if (cc.isValid(itemNode)) {
                        this.storeDataList.content.addChild(itemNode);
                        var comp = itemNode.getComponent("item_node");
                        if (comp) comp.init(itemObj, Utils.ITEM_TYPE_STORE);

                        console.log("add one item");
                        console.log(itemObj);
                    }
                }
            }
        }
    },

    _refreshMarket: function() {
        handler.getAllTransactions();
        var transIds = dataManager.getTransIds();
        for (var i = 0; i < transIds.length; ++i) {
            if (transIds[i] && transIds[i] > 0) {
                handler.getTransactionInfo(transIds[i]);
            }
        }

        this.marketDataList.content.removeAllChildren();
        var marketItems = dataManager.getMarketItems();
        for (var i = 0; i < marketItems.length; ++i) {
            if (marketItems[i] && marketItems[i].tokenId > 0) {
                var sellItemNode = cc.instantiate(this.marketPrefab);
                if (cc.isValid(sellItemNode)) {
                    this.marketDataList.content.addChild(sellItemNode);
                    var comp = sellItemNode.getComponent("marketItem");
                    if (comp) comp.init(marketItems[i]);
                }
            }
        }
    },

    resetExplore: function() {
        this.exploreLabel.node.active = false;
        this.time.node.active = false;
        this.exploreBtn.node.active = true;
        this.unschedule(this.updateTime);
        
        this.unschedule(this.checkExplore);
    },

    updateTime: function() {
        this._time++;
        this.time.string = getDate(this._time);
    },

    updateRewards: function(rewards) {
        alert("冒险完成，获得奖励请查看仓库");
        this.scheduleOnce(function() {
            handler.getPlayer();
        }, 1);
    },

    onClickExplore: function() {
        var self = this;
        
        var food;
        var baglist = [];
        var itemList = dataManager.getItemList();
        for (var i = 0; i < itemList.length; ++i) {
            if (itemList[i].itemId.substr(0, 1) == '1' || itemList[i].itemId.substr(0, 1) == '2') {
                food = itemList[i].tokenId;
                break;
            }
        }
        if (!food) {
            alert("食物不足，暂时不能冒险！");
            return;
        }

        var bagItems = this.bagDataList.content.children;
        if (bagItems.length > 4) {
            alert("背包最多携带四个物品");
            return;
        }
        for (var i = 0; i < bagItems.length; ++i) {
            var bagitem = bagItems[i].getComponent("item_node").getItem();
            if(bagitem.tokenId != food) baglist.push(bagitem.tokenId);
        }
        var itemListObj = {
            bagList: baglist,
            conditions: [1, 2, 3, 4]
        }
        handler.adventure(food, JSON.stringify(itemListObj));

        this.schedule(this.checkExplore, 3);

        eventManager.fire(eventManager.START_EXPLORE);

        this.exploreLabel.node.active = true;
        this.time.node.active = true;
        this.exploreBtn.node.active = false;
        this.schedule(this.updateTime, 1);
    },

    checkExplore: function() {
        console.log("checkExplore");
        handler.getAdventureInfo();
    },

    onExploreFinish: function(cmd, bagList, rewards) {
        this.resetData();
        this.resetExplore();
        this.updateRewards(rewards);

        eventManager.fire(eventManager.END_EXPLORE);
    },

    onClickNewLand: function() {
        this.newLandNode = cc.instantiate(this.newLand);
        if (cc.isValid(this.newLandNode)) {
            this.node.addChild(this.newLandNode);
        }
    },

    onClickStoreType: function(eventid, type) {
        this.storeDataList.content.removeAllChildren();
        var itemList = dataManager.getItemList();
        for (var i = 0; i < itemList.length; ++i) {
            var itemObj = itemList[i];
            if (itemObj) {
                if (itemObj.itemId.substr(0, 1) == type || type == '0') {
                    for (var j = 0; j < itemObj.useCount; ++j) {
                        var itemNode = cc.instantiate(this.item);
                        if (cc.isValid(itemNode)) {
                            this.storeDataList.content.addChild(itemNode);
                            var comp = itemNode.getComponent("item_node");
                            if (comp) comp.init(itemObj, Utils.ITEM_TYPE_STORE);
                        }
                    }
                }
            }
        }
    },

    onDataChange: function() {
        this._refreshStore();
        this._refreshMarket();
    },

    onItemChange: function(cmd, itemType, item) {
        if (!item) return;
        if (itemType == Utils.ITEM_TYPE_STORE) {
            var children = this.storeDataList.content.children;
            if (children.length >= 1) {
                for (var i = 0; i < children.length; ++i) {
                    var itemNode = children[i];
                    var itemNodeObj = itemNode.getComponent("item_node").getItem();
                    if (itemNodeObj.tokenId == item.tokenId) {
                        this.storeDataList.content.removeChild(itemNode);
                        this.bagDataList.content.addChild(itemNode);
                        itemNode.getComponent("item_node").setItemType(Utils.ITEM_TYPE_BAG);
                    }
                }
            }
        } else if (itemType == Utils.ITEM_TYPE_BAG) {
            var children = this.bagDataList.content.children;
            if (children.length >= 1) {
                for (var i = 0; i < children.length; ++i) {
                    var itemNode = children[i];
                    var itemNodeObj = itemNode.getComponent("item_node").getItem();
                    if (itemNodeObj.tokenId == item.tokenId) {
                        this.bagDataList.content.removeChild(itemNode);
                        this.storeDataList.content.addChild(itemNode);
                        itemNode.getComponent("item_node").setItemType(Utils.ITEM_TYPE_STORE);
                    }
                }
            }
        }
        this._refreshExploreData();
    },
    resetData: function() {
        // this.storeDataList.content.removeAllChildren();
        this.bagDataList.content.removeAllChildren();
    },
});
